package com.speaktoitcookbook.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.speaktoitcookbook.bean.Cookbook;
import com.speaktoitcookbook.dao.ICollectionDao;
import com.speaktoitcookbook.dao.factory.DaoFactory;
import com.speaktoitcookbook.util.LogUtil;

@WebServlet("/MyCollectionService")
public class MyCollectionService extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger log = LogUtil
            .getLogger(MyCollectionService.class);

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        String userID = request.getParameter("userID");
        List<Cookbook> cookBooks = null;

        ICollectionDao dao = DaoFactory.getCollectionDao();

        try {
            cookBooks = dao.getCollections(userID);
        } catch (Exception e) {
            log.error(e);
        }

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        String msg = gson.toJson(cookBooks);
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();

        log.info("用户:" + userID + "访问收藏信息:" + msg);
    }

}